Page({
    data: {
        translateZ: '0px',
        selectedCard: null,
        transformedDataArray: [],
        items: [],
        cardShow: false,
        animationClass: '' // 空的字符串，以便我们动态地为卡片添加不同的动画类
    },
    onLoad(options) {
        // 设置上边栏文字样式和背景颜色
        wx.setBackgroundTextStyle({
            textStyle: 'light' // 设置为深色背景后文字为白色
        })
  
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#000000'
        })


        const that = this;
        /**生成背景星星-开始 */ 
        var stars = 400; 
        var r = 0; 
        var stararray = []; 
        for (var i = 0; i < stars; i++) { 
        var s = 0.2 + Math.random() * 1; 
        var curR = r + Math.random() * 300; 
        var rotateY = Math.random() * 360; 
        var rotateX = Math.random() * -50; 
        stararray[i] = { curR: curR, rotateY: rotateY, rotateX: rotateX, s: s }; 
        } 
        // console.log(stararray) 
        this.setData({ 
        stararray: stararray, 
        }) 
		wx.getSystemInfo({
			success: (res) => {
				that.setData({
					translateZ: (res.windowWidth / 2 - 20) + 'px'
				});
			}
		});
    },



    toggleBtnAndSendRequest: function(e) {
        let index = this.data.ThisIndex;  // 从data-index中获取index
        let currentStatus = this.data.btnStatus[index];  // 获取当前页面的按钮状态
        let newStatus = !currentStatus;  // 翻转状态
        
        let apiUrl = newStatus ? 'http://47.95.223.130:8083/Custom/add' : 'http://47.95.223.130:8083/Custom/del';  // 根据状态选择API
        // console.log(JSON.stringify(this.data.transformedDataArray[index]))
        wx.request({
          url: apiUrl,
          method: 'POST',
          data: {
            userId: this.data.userInfo.uuid,
            word: JSON.stringify(this.data.items[index]),
            word_id: this.data.items[index].word_id,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: res => {
            //  console.log(JSON.stringify(this.data.transformedDataArray[index]))
            //  console.log(this.data.transformedDataArray[index].word_id)
            console.log(res);
            console.log(this.data.items[index].word_id)
            if (res.data.code === 200) {
                console.log(res.data.message)
              
            }
          },
          fail: res => {
            wx.showToast({
              title: '网络请求失败',
              icon: 'none',
              duration: 2000
            });
          }
        });
    
        // 更新这个页面的状态
        this.setData({
          [`btnStatus[${index}]`]: newStatus
        });
      },
    



    //...
     play() {
        var userInfo = wx.getStorageSync('userInfo');
        var bookId = wx.getStorageSync('bookId');
        this.setData({ 
            userInfo: userInfo,
            bookId: bookId,
        });
        var userId1 = wx.getStorageSync('userId');
        this.setData({
            userId: userId1,
        });

        wx.request({
            url: 'http://47.95.223.130:8083/Word/request',
            data: {
                userId: this.data.userInfo.uuid,
                bookId: this.data.bookId,
            },
            method: "POST",
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },     
            success: res => {

                let transformedData = [];

                res.data.data.forEach(item => {
                    let parsedWord = JSON.parse(item.word);
                    parsedWord.word_id = item.word_id;
                    transformedData.push(parsedWord);
                });

                if (transformedData.length > 9) {
                    transformedData.push(transformedData[9]);
                    transformedData.push(transformedData[3]);
                } else {
                    // Handle the case when transformedData has less than 10 elements
                }

                this.setData({
                    transformedDataArray: transformedData
                });

                this.setData({
                    items: transformedData
                });

                let initStatus = Array(transformedData.length).fill(false);
                    this.setData({
                        btnStatus: initStatus
                    });

                this.animate('#carousel_id', [
                    { ease: 'ease', rotateY: 0 },
                    { ease: 'ease', rotateY: 3600 }
                ], 5000, function () {
                    console.log('回调成功，旋转结束');
                }.bind(this));
            },
            fail: res => {
                // Handle error case
            }
        });
    },

    cardClick(event) {
        // added check if card is already showing
        var that = this;
        if(this.data.cardShow) {
            console.log("显示卡片失效")
          return; // Do nothing if card is already showing
        } else {
            that.setData({
                cardShow: true, // 显示卡片
                animationClass: 'animate__animated animate__flip' // 切换到显示动画
              });
            var item = event.currentTarget.dataset.item;
            var ThisIndex = event.currentTarget.dataset.index;
            //console.log(ThisIndex)
            that.setData({ 
                selectedCard: item,
                ThisIndex: ThisIndex,
             });
            console.log(this.data.selectedCard)
            console.log(this.data.ThisIndex)
            console.log(this.data.items[ThisIndex])
            //wx.setStorageSync('selectedCard', this.data.selectedCard);
        }
        
    },
    //...

    
    // 触发显示动画的函数
    cardShowFunc: function() {
        // added check if card is already showing
        if(this.data.cardShow) {
            console.log("显示卡片失效")
          return; // Do nothing if card is already showing
        }
        this.setData({
          cardShow: true, // 显示卡片
          animationClass: 'animate__animated animate__flip' // 切换到显示动画
        });
      },
    
      // 触发隐藏动画的函数
      cardHideFunc: function() {
        this.setData({
          animationClass: 'animate__animated animate__flipOutY' // 切换到隐藏动画
        });
    
        //设置延迟以等待动画完成后再移除卡片（这里我们假设动画的持续时间大约是1秒）
        setTimeout(() => {
          this.setData({
            cardShow: false // 隐藏卡片
          });
        }, 1000); 
      },
})
